package com.lxu.service;

import com.lxu.entity.ReportDirEntity;
import com.lxu.entity.ReportExportConfigEntity;
import com.lxu.entity.bo.ReportTableBO;
import com.lxu.entity.enums.ReportEnum;
import com.lxu.util.ReportToolsConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 模板数据组装 服务类
 */
@Service("sdweweew")
public class TemplateDataAssembleService {

    @Autowired
    private TemplateQueryService templateQueryService;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public void generateTemplateData(ReportDirEntity dir, Map<String, Object> templateTextMap, Map<String, List<List<String>>> templateTableMap, List<ReportTableBO> templateTables) {
        if (StringUtils.isNotBlank(dir.getDataSql())) {
            //执行数据集SQL脚本
            executeSql(templateTextMap, dir.getDataSql());
        }
        if (ReportEnum.DATA_TYPE.SINGLE_DATA.getValue().equals(dir.getDataType())) {
            return;
        } else {
            List<ReportExportConfigEntity> exports = templateQueryService.queryDataByDir(dir.getId());
            if (CollectionUtils.isEmpty(exports)) {
                return;
            }
            for (ReportExportConfigEntity export : exports) {
                executeSql(templateTextMap, templateTableMap, templateTables, export);
            }
        }
    }

    /**
     * 模板导出配置表中可能存在表单，也可能存在表格
     *
     * @param templateTextMap
     * @param templateTableMap
     * @param templateTables
     * @param export
     */
    private void executeSql(Map<String, Object> templateTextMap,
                            Map<String, List<List<String>>> templateTableMap,
                            List<ReportTableBO> templateTables,
                            ReportExportConfigEntity export) {
        if (ReportEnum.DATA_TYPE.SINGLE_DATA.getValue().equals(export.getMetaType())) {
            executeSql(templateTextMap, export.getDataSql());
        } else {
            Map<String, List<List<String>>> map = executeTableSql(templateTableMap, export.getDataSql(), export.getTableIndex());
            if (map != null) {
                ReportTableBO reportTableBO = new ReportTableBO();
                reportTableBO.setTemplateTables(map);
                reportTableBO.setExportConfigEntity(export);
                templateTables.add(reportTableBO);
            }
        }
    }

    /**
     * 执行数据集sql,封装到table map中
     *
     * @param templateTableMap
     * @param dataSql
     */
    private Map<String, List<List<String>>> executeTableSql(Map<String,
            List<List<String>>> templateTableMap, String dataSql, int tableIndex) {
        if (StringUtils.isBlank(dataSql)) {
            return null;
        }

        String columns = dataSql.substring(dataSql.toLowerCase().indexOf("select") + 6, dataSql.toLowerCase().indexOf("from")).trim();

        String[] sqlColumns = columns.split(",");

        for (int i = 0; i < sqlColumns.length; i++) {
            //sqlColumns[i] = CommonUtils.underline2Camel(sqlColumns[i].trim().substring(1,sqlColumns[i].length()));
            sqlColumns[i] = sqlColumns[i].trim().substring(2, sqlColumns[i].length());
        }


        List<Map<String, Object>> result = jdbcTemplate.queryForList(dataSql);
        if (result == null) {
            return null;
        }
        List<List<String>> values = new ArrayList<List<String>>();
        for (Map<String, Object> map : result) {
            List<String> list = new ArrayList<String>();
            for (String sqlColumn : sqlColumns) {
                list.add((String) map.get(sqlColumn));
            }
            values.add(list);
        }
        templateTableMap.put(ReportToolsConstant.TABLE_PREFIX + tableIndex, values);
        return templateTableMap;
    }

    /**
     * 执行数据集sql，封装到占位符 map中
     *
     * @param templateTextMap
     * @param dataSql
     */
    private void executeSql(Map<String, Object> templateTextMap, String dataSql) {
        if (StringUtils.isBlank(dataSql)) {
            return;
        }
        Map<String, Object> result = jdbcTemplate.queryForMap(dataSql);
        if (result == null) {
            return;
        }
        Iterator iterator = result.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            templateTextMap.put(entry.getKey().toString(), entry.getValue());
        }
    }
}
